/*
*
on订阅/监听

emit 发布/注册

once 只执行一次

off解除绑定
*
*/

interface EventFace {
  on: (name:string,callback:Function) => void
  emit: (name:string,...args:Array<any>) => void
  off: (name:string,fn:Function) => void
  once: (name:string,fn:Function) => void
}

interface List {
  [key: string] : Array<Function>
}

export class Dispatch implements EventFace{
  
  list:List
  constructor(){
    this.list = {}
  }

  on(name:string,callback:Function){
    const callbackList: Array<Function> = this.list[name] || []
    callbackList.push(callback)
    this.list[name] = callbackList
  }

  emit(name:string,...args:Array<any>){
    let eventName = this.list[name]
    if(eventName){
      eventName.forEach(item=>{
        item.apply(this,args)
      })

    }else{
      console.error('该事件未监听！')
    }

  }

  off(name:string,fn:Function){
    let eventName = this.list[name]
    if(eventName && fn){
      let index =  eventName.findIndex(item => item === fn)
      eventName.splice(index,1)

    }else{
      console.error('该事件未监听！')
    }

  }
  
  once(name:string,fn:Function){
    let decor = (...args:Array<any>) => {
      fn.apply(this,args)
      this.off(name,decor)
    }
  }
}